package com.doudou.collection.infrastructure.common.security;

import com.doudou.collection.infrastructure.common.ex.ServiceException;
import com.doudou.collection.infrastructure.common.web.StatusCode;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @ClassName SecurityUtils<br>
 * @Description 安全服务工具类<br>
 * @Author 李浩文<br>
 * @Date 2023/6/27 17:24<br>
 * @Version 1.0<br>
 */
public class SecurityUtils {

    /**
     * 用户ID
     **/
    public static Long getUserId() {
        return getLoginUser().getUserId();
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        return getLoginUser().getUsername();
    }

    /**
     * 获取用户
     */
    public static CurrentPrincipal getLoginUser() {
        try {
            return (CurrentPrincipal) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceException(StatusCode.NOT_LOGIN);
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 是否为管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId) {
        return userId != null && 1L == userId;
    }
}